package cn.lin.service.impl;

import cn.lin.dao.UserRepository;
import cn.lin.domain.Organization;
import cn.lin.domain.User;
import cn.lin.mapper.OrganizationMapper;
import cn.lin.mapper.UserMapper;
import cn.lin.service.UserService;
import cn.lin.util.ImportExcelUtil;
import cn.lin.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qmp
 * @date 2024/12/3 11:52
 */
@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper ;

    @Autowired
    private OrganizationMapper organizationMapper ;

    @Autowired
    private UserRepository userRepository ;


    @Override
    public List<User> findByNameLike(String username) {

        List<User> users = userRepository.findByUsername(username);

        return users ;
    }

    public Map<String,Object> importTprkxx(MultipartFile file, int organizationId){
        Map<String,Object> resultMap = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        List<User> userList = new ArrayList<>();

        try {

            //验证文件类型
            if (!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xls")&&!file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")).equals(".xlsx")){
                resultMap.put("mete", "文件类型有误！请上传Excle文件");
                throw new Exception("文件类型有误！请上传Excle文件");
            }

            //获取数据
            List<List<Object>> olist = ImportExcelUtil.getListByExcel(file.getInputStream(), file.getOriginalFilename());

            resultMap.put("导入成功",200);
            //封装数据
            for (int i = 0; i < olist.size(); i++) {
                List<Object> list = olist.get(i);
                if (list.get(0) == "" || ("序号").equals(list.get(0))) {
                    continue;
                }
                User user = new User();
//                stu.setId(UUID.randomUUID().toString().replace("-", "").substring(0, 20));
                //根据下标获取每一行的每一条数据
                if (String.valueOf(list.get(0))==null||String.valueOf(list.get(0)).equals("")) {
                    resultMap.put("mete", "机构名称不能为空");
                    throw new Exception("机构名称不能为空");
                }
                String organizationName = String.valueOf(list.get(0)) ;

                Integer id = organizationMapper.findIdByName(organizationName) ;
                //如果id是空，说明是新的组织，就需要对机构表进行新增
                if (id == null){
                    organizationMapper.add(organizationId,2,organizationName) ;
                }
                //无论怎样再次查询，将机构实体查出来并放入用户对象中
                Organization organization = organizationMapper.findByName(organizationName);
                user.setOrganization(organization);

                if (String.valueOf(list.get(1))==null||String.valueOf(list.get(1)).equals("")) {
                    resultMap.put("mete", "姓名不能为空");
                    throw new Exception("姓名不能为空");
                }
                user.setUsername(String.valueOf(list.get(1)));

                if (String.valueOf(list.get(2))==null||String.valueOf(list.get(2)).equals("")) {
                    resultMap.put("mete", "密码不能为空");
                    throw new Exception("密码不能为空");
                }
                user.setPwd(String.valueOf(list.get(2)));

                if (String.valueOf(list.get(3))==null||String.valueOf(list.get(3)).equals("")) {
                    resultMap.put("mete", "导入失败,上报时间不能为空");
                    throw new Exception("导入失败,上报时间不能为空");
                }
                user.setTel(String.valueOf(list.get(3)));

                /*if (String.valueOf(list.get(8))==null||String.valueOf(list.get(8)).equals("")) {
                    resultMap.put("mete", "导入失败,创建时间不能为空");
                    throw new Exception("导入失败,创建时间不能为空");
                }
                try {
                    tbZbzs.setCreateDate(simpleDateFormat.parse(String.valueOf(list.get(8))));
                }catch (ParseException e){
                    resultMap.put("mete","请填写正确的时间格式！");
                    throw new Exception("请填写正确的时间格式！");
                }*/
                userList.add(user);
            }

            int i = userMapper.insertUserList(userList);

            //将新增的学生同时添加到es中
            for (User user : userList){
                userRepository.save(user) ;
            }

            int j = organizationMapper.insertList(userList) ;
            int k = userMapper.insertList2userRole(userList) ;
            System.out.println("这是插入数据之后返回的id----------" + userList.get(1).getId());
            if (i != 0 && j != 0 && k != 0) {
                resultMap.put("state", 200);
            }else {
                resultMap.put("mete","文档内无数据，请重新导入");
                resultMap.put("state", 500);
            }

        } catch (Exception e) {
            e.printStackTrace();

        }finally {
            return resultMap;
        }
    }

    @Override
    public List<UserVO> findUserVO(String tel, String pwd) {
        return userMapper.findUserVO(tel, pwd);
    }

    @Override
    public int updatePhone(Integer id, String tel) {
        return userMapper.updatePhone(id,tel);
    }

    @Override
    public int updateNickname(Integer id, String username) {
        return userMapper.updateNickname(id,username);
    }

    @Override
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override
    public List<User> findAllStudent(Integer organizationId) {

        return userMapper.findAllStudent(organizationId) ;

    }

    @Override
    public boolean importAll() {
        List<User> list = userMapper.findAllStu();
        for (User user : list) {
            userRepository.save(user);
        }
        return true;
    }

    @Override
    public List<User> findAllStu() {

        return userMapper.findAllStu();

    }

    @Override
    public List<User> findClassStu(Integer classId) {

        return userMapper.findClassStu(classId) ;
    }

    @Override
    public int delClassStuByStuId(Integer classId,Integer userId) {

        return userMapper.delClassStuByStuId(classId,userId) ;
    }

    //添加课程学生
    @Override
    public int addClassStu(Integer classId, List<Integer> studentsId) {

        return userMapper.addClassStu(classId,studentsId) ;
    }
}
